package com.godot.entity.checher;

import java.util.ArrayList;
import java.util.Collection;

import javax.jdo.JDODataStoreException;
import javax.jdo.JDOFatalUserException;
import javax.jdo.JDOUserException;
import javax.jdo.PersistenceManager;

import com.godot.entity.persistent.Godot;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class EntityUtil {

	protected PersistenceManager _pm;
	
	public EntityUtil(PersistenceManager pm) {
		this._pm = pm;
	}
	
	private Godot godotById(Key godotKey) {
		try {
			return _pm.getObjectById(Godot.class, godotKey);
		} catch (JDOUserException e) {
			e.printStackTrace();
			return null;
		} catch (JDODataStoreException e) {
			e.printStackTrace();
			return null;
		} catch (JDOFatalUserException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private Godot godotByName(String name) {
		String qName = name.toLowerCase().trim();
		javax.jdo.Query query = _pm.newQuery("select key from " + Godot.class.getName() + " where name == godotName");
		query.declareParameters("String godotName");
		query.setUnique(true);
		Key key = (Key) query.execute(qName);
		
		if (key == null) {
			return null;
		}
		return godotById(key);
	}
	
	public Godot getGodotByName(String name) {
		Godot godot = this.godotByName(name);
		//在这里加上对godot的初始化操作
		return godot;
	}
	
	public Godot getGodotById(String key) {
		return godotById(KeyFactory.stringToKey(key));
	}
	
	public Godot insertGodot(Godot godot) {
		return _pm.makePersistent(godot);
	}
	
	public void deleteObject(Object ob) {
		if (ob != null) {
			_pm.deletePersistent(ob);
		}
	}
	
	@SuppressWarnings("rawtypes")
	public void deleteObjectAll(Collection obs) {
		if (obs != null) {
			_pm.deletePersistentAll(obs);
		}
	}
	
	@SuppressWarnings("unchecked")
	public <T> T getObjectByKey(Class<? extends Object> T, Key key) {
		try {
			return (T) _pm.getObjectById(T, key);
		} catch (JDOUserException e) {
			e.printStackTrace();
			return null;
		} catch (JDODataStoreException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> Collection<T> getObjectsByKey(Class T, Collection<? extends Object> keys) {
		try {
			Collection<Object> ids = new ArrayList<Object>();
			for (Object key : keys) {
				ids.add(_pm.newObjectIdInstance(T, key));
			}
			return _pm.getObjectsById(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
}
